﻿using HotChocolate.Execution;
using HotChocolate.Stitching.Pipeline;

namespace HotChocolateDemo.Host.Infrastructures
{
    public class JwtHttpStitchingRequestInterceptor : IHttpStitchingRequestInterceptor
    {
        private readonly IHttpContextAccessor _httpContextAccessor;

        public JwtHttpStitchingRequestInterceptor(IHttpContextAccessor httpContextAccessor)
        {
            _httpContextAccessor = httpContextAccessor;
        }

        public ValueTask OnCreateRequestAsync(string targetSchema, IQueryRequest request, HttpRequestMessage requestMessage, CancellationToken cancellationToken = default)
        {
            var authorization = _httpContextAccessor.HttpContext!.Request.Headers.Authorization.ToString().Replace("Bearer ", "");
            requestMessage.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", authorization);
            return default;
        }

        public ValueTask<IQueryResult> OnReceivedResultAsync(string targetSchema, IQueryRequest request, IQueryResult result, HttpResponseMessage responseMessage, CancellationToken cancellationToken = default)
        {
            return new ValueTask<IQueryResult>(result);
        }
    }
}
